<script setup lang="ts">
import { getImageList, getInstanceList, pullImage, removeImage } from '@/api/docker';
import type {Image, Instance} from '@/api/docker/type';
import type { TabsPaneContext } from 'element-plus';
import { onMounted, ref } from 'vue';

const instanceList = ref([] as Instance[])
const imageList = ref([] as Image[])
const activeIndex = ref(0)
const pullShow = ref(false);
const imageName = ref('');
const handleClick = (tab: TabsPaneContext, event: Event) => {
  init();
}
const init = async () => {
    const res = await getInstanceList();
    instanceList.value = res.data as Instance[];
    refresh(activeIndex.value);
}
onMounted(() => {
    init();
})
const refresh = (index: number) => {
    const instanceId = instanceList.value[index].id;
    getImageList(instanceId).then((res) => {
        imageList.value = res.data as Image[];
    })
}

const openRemove = (image: Image) => {
    const instanceId = instanceList.value[activeIndex.value].id;
    removeImage(instanceId, image.id).then((res) => {
        refresh(activeIndex.value);
    });
}

const openPullImage = () => {
    const instanceId = instanceList.value[activeIndex.value].id;
    pullImage(instanceId, imageName.value).then((res) => {
        console.log(res);
    });
}
</script>

<template>
    <div class="content">
        <el-tabs v-model="activeIndex" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane v-for="(item, index) in instanceList" :label="item.name" :name="index"></el-tab-pane>
        </el-tabs>
        <el-button type="primary" @click="pullShow = true;">拉取镜像</el-button>
        <el-table class="table" :data="imageList" style="width: 100%" stripe border>
            <el-table-column prop="id" label="镜像ID" />
            <el-table-column prop="tag" label="镜像TAG" />
            <el-table-column prop="created" label="创建时间" />
            <el-table-column fixed="right" label="操作" min-width="100">
                <template #default="scope: {row: Image}">
                    <el-button link type="primary" @click="openRemove(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-dialog
            v-model="pullShow"
            title="拉取镜像"
            width="500"
        >
            <el-input v-model="imageName" style="width: 240px" placeholder="Please input image tag" />
            <el-button type="primary" @click="openPullImage">拉取</el-button>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
.content {
    height: 100%;
    .table {
        height: 80%;
        overflow-y: scroll;
    }
}
</style>